import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class TankClient extends Frame {
	public static int GAME_WIDTH;
	public static int GAME_HEIGHT;

	Tank myTank = new Tank(50, 50, true, Direction.STOP, this);
	List<Wall> walls = new ArrayList<>();
	List<WallExplode> wallExplodes = new ArrayList<>();
	List<Explode> explodes = new ArrayList<>();
	List<Missile> missiles = new ArrayList<>();
	List<Tank> tanks = new ArrayList<>();
	List<Blood> bloods = new ArrayList<>();
	Image offScreenImage = null;
	private static Toolkit tk = Toolkit.getDefaultToolkit();
	static Image backGround = null;
	private Random random = new Random();
	private Timer bloodTimer;
	private int maxBloodCount;
	private long respawnTime;


	static {
		backGround = tk.getImage(TankClient.class.getClassLoader().getResource("images/background.jpg"));
		AudioUtil.initAudio();
	}

	public void paint(Graphics g) {
		g.drawString("子弹数量:" + missiles.size(), 10, 50);
		g.drawString("爆炸效果:" + explodes.size(), 10, 70);
		g.drawString("敌方坦克:" + tanks.size(), 10, 90);
		g.drawString("我的生命:" + myTank.getLife(), 10, 110);
		g.drawString("血包数量:" + bloods.size(), 10, 130);

		if (tanks.size() <= 0) {
			int count = Integer.parseInt(PropertyMgr.getProperty("reProduceTankCount"));
			for (int i = 0; i < count; i++) {
				tanks.add(new Tank(50 + 40 * (i + 1), 50, false, Direction.D, this));
			}
		}

		for (int i = 0; i < missiles.size(); i++) {
			Missile m = missiles.get(i);
			m.hitTanks(tanks);
			m.hitTank(myTank);
			for (Wall wall : walls) {
				if (m.hitWall(wall)) {
					wall.hitByMissile();
				}
			}
			m.draw(g);
		}

		for (int i = 0; i < explodes.size(); i++) {
			Explode e = explodes.get(i);
			e.draw(g);
		}

		for (int i = 0; i < wallExplodes.size(); i++) {
			WallExplode e = wallExplodes.get(i);
			e.draw(g);
		}

		for (int i = 0; i < tanks.size(); i++) {
			Tank t = tanks.get(i);
			t.draw(g);
		}
		myTank.draw(g);

		walls.removeIf(Wall::isNeedRemove);
		for (Wall wall : walls) {
			wall.draw(g);
		}

		for (int i = 0; i < bloods.size(); i++) {
			Blood b = bloods.get(i);
			if (b.isLive()) {
				b.draw(g);
				if (myTank.eat(b)) {
					bloods.remove(i);
					i--;
				}
			}
		}
	}

	public void update(Graphics g) {
		if (offScreenImage == null) {
			offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
		}
		Graphics gOffScreen = offScreenImage.getGraphics();
		Color c = gOffScreen.getColor();
		gOffScreen.setColor(Color.BLACK);
		gOffScreen.drawImage(backGround, 0, 0, GAME_WIDTH, GAME_HEIGHT, null); // 拉伸背景
		gOffScreen.setColor(c);
		paint(gOffScreen);
		g.drawImage(offScreenImage, 0, 0, null);
	}

	private void initWalls() {
		try {
			String wallCountStr = PropertyMgr.getProperty("wallCount");
			if (wallCountStr == null || wallCountStr.trim().isEmpty()) {
				throw new IllegalArgumentException("wallCount 配置缺失");
			}

			wallCountStr = wallCountStr.replaceAll("[^0-9]", "");
			int wallCount = Integer.parseInt(wallCountStr);

			for (int i = 0; i < wallCount; i++) {
				int x = random.nextInt(GAME_WIDTH - 100) + 50;
				int y = random.nextInt(GAME_HEIGHT - 100) + 50;
				int w = random.nextInt(100) + 30;
				int h = random.nextInt(100) + 30;
				walls.add(new Wall(x, y, w, h, this));
			}
		} catch (NumberFormatException e) {
			System.err.println("墙壁数量配置错误，使用默认值");
			walls.add(new Wall(100, 200, 20, 150, this));
			walls.add(new Wall(300, 100, 300, 20, this));
		} catch (Exception e) {
			System.err.println("初始化墙壁失败: " + e.getMessage());
			walls.add(new Wall(100, 200, 20, 150, this));
			walls.add(new Wall(300, 100, 300, 20, this));
		}
	}

	private void initBloods() {
		try {
			int initialBloodCount = Integer.parseInt(PropertyMgr.getProperty("initialBloodCount"));

			for (int i = 1; i <= 5; i++) {
				String posConfig = PropertyMgr.getProperty("bloodPos" + i);
				if (posConfig != null && !posConfig.isEmpty()) {
					String[] xy = posConfig.split(",");
					if (xy.length == 2) {
						int x = Integer.parseInt(xy[0].trim());
						int y = Integer.parseInt(xy[1].trim());
						bloods.add(new Blood(x, y));
						initialBloodCount--;
						if (initialBloodCount <= 0) break;
					}
				}
			}

			while (initialBloodCount > 0) {
				bloods.add(new Blood());
				initialBloodCount--;
			}
		} catch (Exception e) {
			e.printStackTrace();
			bloods.add(new Blood(GAME_WIDTH/2, GAME_HEIGHT/2));
		}
	}

	public void launchFrame() {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		GAME_WIDTH = (int) screenSize.getWidth();
		GAME_HEIGHT = (int) screenSize.getHeight();
		initWalls();
		initBloods();
		myTank.setWalls(walls);
		maxBloodCount = Integer.parseInt(PropertyMgr.getProperty("maxBloodCount"));
		respawnTime = Long.parseLong(PropertyMgr.getProperty("bloodRespawnTime"));

		int initTankCount = Integer.parseInt(PropertyMgr.getProperty("initTankCount"));
		for (int i = 0; i < initTankCount; i++) {
			tanks.add(new Tank(50 + 40 * (i + 1), 50, false, Direction.D, this));
		}
		for (Tank t : tanks) {
			t.setWalls(walls);
		}
		this.setSize(GAME_WIDTH, GAME_HEIGHT);
		this.setTitle("坦克大战");
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		//this.setUndecorated(true);
// 将原来的固定值替换为屏幕大小
		this.setSize(GAME_WIDTH, GAME_HEIGHT);
		this.setExtendedState(Frame.MAXIMIZED_BOTH); // 最大化
		this.setBackground(Color.GREEN);
		this.addKeyListener(new KeyMonitor());

		this.setBackground(Color.GREEN);
		this.addKeyListener(new KeyMonitor());
		setVisible(true);

		bloodTimer = new Timer();
		bloodTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				if (bloods.size() < maxBloodCount) {
					bloods.add(new Blood());
				}
			}
		}, respawnTime, respawnTime);

		new Thread(new PaintThread()).start();
	}

	public static void main(String[] args) {
		TankClient tc = new TankClient();
		tc.launchFrame();
	}

	private class PaintThread implements Runnable {
		public void run() {
			while (true) {
				repaint();
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private class KeyMonitor extends KeyAdapter {
		public void keyReleased(KeyEvent e) {
			myTank.keyReleased(e);
		}

		public void keyPressed(KeyEvent e) {
			myTank.keyPressed(e);
			if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
				AudioUtil.playShootSound();
			}
		}
	}
}
